import Zdb from '../../packages/zdb-js/src/Zdb.js';
import db from '@/config/db';

const $zdb = Zdb(db);
const tableName = 'desktop';
export const findDataByKey = (key) => 
{
    return new Promise((resolve, reject) => 
    {
        $zdb.then((res) => 
        {
            res.query_by_primaryKey({
                tableName,
                target:key,
                success:(result) =>
                {
                    if (result)
                    {
                        resolve(result.data);
                        return;
                    }
                    resolve([]);
                }
            });
        },
        (err) => 
        {
            console.log('indexedDB 数据查找失败' + err);
            reject(err);
        });
    });
};

export const setDataByKey = (key, data) => 
{
    return new Promise((resolve, reject) => 
    {
        $zdb.then((res) => 
        {
            res.insert({
                tableName,
                data:{
                    key,
                    data
                },
                success:() => 
                {
                    console.log('indexedDB 数据插入成功');
                    resolve(true);
                }
            });
        },
        (err) => 
        {
            console.log('indexedDB 数据插入失败' + err);
            reject(err);
        });
    });
};

export const updateDataByKey = (key, data) => 
{
    return new Promise((resolve, reject) => 
    {
        $zdb.then((res) => 
        {
            res.update_by_primaryKey({
                tableName,
                target:key,
                handle:(val) => 
                {
                    let arr = [] as any;
                    if (data.length) 
                    {
                        data.forEach((item) => 
                        {
                            arr.push(item);
                        });
                    }
                    val['data'] = JSON.parse(JSON.stringify(arr));
                },
                success:(val) => 
                {
                    console.log('indexedDB 数据更新成功');
                    resolve(true);
                }
            });
        },
        (err) => 
        {
            console.log('indexedDB 数据更新失败' + err);
            reject(err);
        });
    });
};

export const removeDataByKey = (key) => 
{
    return new Promise((resolve, reject) => 
    {
        $zdb.then((res) => 
        {
            res.delete_by_primaryKey({
                tableName,
                target:key,
                success:() =>
                {
                    resolve(true);
                }
            });
        },
        (err) => 
        {
            console.log('indexedDB 数据删除失败' + err);
            reject(err);
        });
    });
};